package com.ch.dream.net;
/**
 * 封装了用json与服务器交互的方法
 */
import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

public class MyHttpAPI {
	private static DefaultHttpClient httpClient;
	private  HttpPost httpPost;
	private  HttpGet httpGet;
	private String url;
	public  int timeout = 30;
	
	public MyHttpAPI(){
		if(httpClient==null){
			initHttpClient();
		}
	}
	
	public DefaultHttpClient getDefaultHttpClient(){
		if(httpClient==null){
			initHttpClient();
		}
		return httpClient;
	}
	/**
	 * 初始化httpclient
	 * @throws Exception
	 */
	private void initHttpClient(){
		final SchemeRegistry supportedSchemes = new SchemeRegistry();

		final SocketFactory sf = PlainSocketFactory.getSocketFactory();
		supportedSchemes.register(new Scheme("http", sf, 80));
		supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
		final HttpParams httpParams = createHttpParams();
		HttpClientParams.setRedirecting(httpParams, false);

		final ClientConnectionManager ccm = new ThreadSafeClientConnManager(httpParams, supportedSchemes);
		httpClient = new DefaultHttpClient(ccm, httpParams);
	}
	
	/**
	 * 初始化http参数
	 * @throws Exception
	 */
	private HttpParams createHttpParams() {
		final HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setStaleCheckingEnabled(params, false);

		HttpConnectionParams.setConnectionTimeout(params, timeout * 1000);
		HttpConnectionParams.setSoTimeout(params, timeout * 1000);
		HttpConnectionParams.setSocketBufferSize(params, 8192);
		return params;
	}
	/**
	 * 初始化get，post请求
	 * @throws Exception
	 */
	public MyHttpAPI(String url){
		if(httpClient==null){
			initHttpClient();
		}
		this.url =url;
		httpPost = new HttpPost(url);
		httpGet =new HttpGet(url);
	}
	/**
	 * post方式请求
	 * @throws Exception
	 */
	public HttpResponse requestPost() throws Exception{
		Log.d("net", "url:"+this.url);
		return httpClient.execute(httpPost);
	}
	/**
	 * post方式json传参
	 * @param jsonObject
	 * @throws Exception
	 */
	public HttpResponse requestPost(JSONObject jsonObject) throws Exception{
		httpPost.setEntity(getParamsByJson(jsonObject));
		return requestPost();
	}
	/**
	 * 根据json得到post传输的参数对象
	 * @param jsonObject
	 * @return
	 * @throws Exception
	 */
	private UrlEncodedFormEntity getParamsByJson(JSONObject jsonObject) throws Exception{
		List<NameValuePair> params =new ArrayList<NameValuePair>();
		NameValuePair pair =new BasicNameValuePair("json",jsonObject.toString());
		params.add(pair);
		return new UrlEncodedFormEntity(params,HTTP.UTF_8);
	}
	
	/**
	 * get方式请求
	 * @throws Exception
	 */
	public HttpResponse requestGet() throws Exception{
		Log.d("net", "url:"+this.url);
		return httpClient.execute(httpGet);
	}
	/**
	 * get方式json传参
	 * @param jsonObject
	 * @throws Exception
	 */
	public HttpResponse requestGet(JSONObject jsonObject) throws Exception{
		httpGet.setURI(getParamsURI(jsonObject));
		return requestGet();
	}
	/**
	 * 根据json拼接URI参数
	 * @param jsonObject
	 * @return
	 * @throws Exception
	 */
	private URI getParamsURI(JSONObject jsonObject) throws Exception{
		String url =this.url;
		url += "?json="+URLEncoder.encode( jsonObject.toString(),HTTP.UTF_8);
		URI result = URI.create(url);
		return result;
	}
	
	/**
	 * 获取服务器返回的json数据
	 * @return
	 * @throws Exception
	 */
	public JSONObject requestForJson()throws Exception{
		HttpResponse response = requestGet();
		HttpEntity entity = response.getEntity();
		JSONObject jsonObject =new JSONObject( EntityUtils.toString(entity,HTTP.UTF_8));
		Log.d("net", "result:"+jsonObject.toString());
		return jsonObject;
	}
	/**
	 * 传入json参数并获取返回的json数据
	 * @param jsonObject
	 * @return
	 * @throws Exception
	 */
	public JSONObject requestForJson(JSONObject jsonObject)throws Exception{
		HttpResponse response = requestGet(jsonObject);
		HttpEntity entity = response.getEntity();
		JSONObject result =new JSONObject(EntityUtils.toString(entity,HTTP.UTF_8));
		Log.d("net", "result:"+result.toString());
		return result;
	}
	
	/**
	 * 获取服务器返回的json数据
	 * @return
	 * @throws Exception
	 */
	public JSONArray requestForJsonArray()throws Exception{
		HttpResponse response = requestGet();
		HttpEntity entity = response.getEntity();
		JSONArray jsonArray = new JSONArray(EntityUtils.toString(entity,HTTP.UTF_8));
		Log.d("net", "result:"+jsonArray.toString());
		return jsonArray;
	}
	/**
	 * 传入json参数并获取返回的jsonArray数据
	 * @param jsonObject
	 * @return
	 * @throws Exception
	 */
	public JSONArray requestForJsonArray(JSONObject jsonObject)throws Exception{
		HttpResponse response = requestGet(jsonObject);
		HttpEntity entity = response.getEntity();
		JSONArray jsonArray = new JSONArray(EntityUtils.toString(entity,HTTP.UTF_8));
		Log.d("net", "result:"+jsonArray.toString());
		return jsonArray;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) throws Exception{
		this.url = url;
		if(httpPost==null){
			httpPost = new HttpPost(this.url);
		}else{
			httpPost.setURI(new URI(this.url));
		}
		if(httpGet==null){
			httpGet =new HttpGet(this.url);
		}else{
			httpGet.setURI(new URI(this.url));
		}
	}
}
